
package com.chengyu.eyc.config;

import java.sql.SQLIntegrityConstraintViolationException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import com.chengyu.eyc.base.ResponseResult;
import com.chengyu.eyc.enums.HttpStatusEnum;
import com.github.binarywang.wxpay.exception.WxPayException;

import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;

    /**
     * @return
     */
    private ResponseResult<String> builderResponseResult(HttpStatusEnum httpStatusEnum, String message) {
        ResponseResult<String> responseResult = new ResponseResult<>();
        responseResult.setCode(httpStatusEnum.code());
        responseResult.setMessage(message);
        return responseResult;
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult<String> handleException(Throwable e) {
        log.error(e.getMessage(), e);
        if (e instanceof MaxUploadSizeExceededException) {
            return builderResponseResult(HttpStatusEnum.ERROR_500, "文件大小超出" + maxFileSize + "限制, 请压缩或降低文件质量!");
        } else if (e instanceof WxPayException) {
            return builderResponseResult(HttpStatusEnum.ERROR_400, String.join(":", HttpStatusEnum.ERROR_400.desc(), ((WxPayException)e).getErrCodeDes()));
        } else if (e instanceof DataIntegrityViolationException) {
            DataIntegrityViolationException dataIntegrityViolationException = (DataIntegrityViolationException)e;
            if (dataIntegrityViolationException.getCause() instanceof SQLIntegrityConstraintViolationException) {
                SQLIntegrityConstraintViolationException constraintViolationException = (SQLIntegrityConstraintViolationException)dataIntegrityViolationException.getCause();
                return builderResponseResult(HttpStatusEnum.ERROR_500, constraintViolationException.getMessage());
            }
        } else if (e instanceof HttpMessageNotReadableException) {
            return builderResponseResult(HttpStatusEnum.ERROR_500, "字段类型转换失败~~");
        }
        return builderResponseResult(HttpStatusEnum.ERROR_500, e.getMessage());
    }

}
